<?php
/**
 * Created by PhpStorm.
 * User: wuchao
 * Date: 2020/4/20
 * Time: 11:06
 */

namespace app\api\model;

use \Exception;
use think\facade\Db;
use \think\response\Json;

class AddressModel
{
    private static $_table = 'user'; // 用户表
    private static $_user_address_table = 'company_address'; // 用户地址表
    private static $_dirverTable = 'dirver'; // 司机表
    private static $_dirver_routeTable = 'dirver_route'; // 司机路由表

    /**用户地址列表
     * @param array $input
     * @return Json
     */
    public static function AddressList($input)
    {
        $field = 'id,name,phone as tel,province,city,area,address as dedail,is_default,longitude,latitude';
        $data = Db::table(self::$_user_address_table)->where('status', 1)->where('group_id', $input['group_id'])->field($field)->select()->toArray();
        return jsonSuccess('获取成功', $data);
    }

    /**添加地址
     * @param array $input
     * @return Json
     */
    public static function AddAddress($input)
    {
        try {
            $input['create_time'] = time();
            $res = Db::table(self::$_user_address_table)->insertGetId($input);
            if ($input['is_default'] == 1) {
                $red = Db::table(self::$_user_address_table)->where('group_id',$input['group_id'])->where('status',1)->where('id', '<>', $res)->update(['is_default' => 0]);
            }
            if ($res != 0) return jsonSuccess('添加成功', $res);
            return jsonFail('添加失败');
        } catch (\Exception $e) {
            return jsonFail($e->getMessage());
        }
    }

    /**修改地址
     * @param array $input
     * @return Json
     */
    public static function EditAddress($input)
    {
        try {
            $red = Db::table(self::$_user_address_table)->where('id', $input['id'])->update($input);
            if ($input['is_default'] == 1) {
                $res = Db::table(self::$_user_address_table)->where('group_id', $input['group_id'])->where('id', '<>', $input['id'])->update(['is_default' => 0]);
            }
            if ($red != 0) return jsonSuccess('修改成功', $red);
            return jsonFail('修改失败');
        } catch (\Exception $e) {
            return jsonFail($e->getMessage());
        }
    }

    /**删除地址
     * @param array $input
     * @return Json
     */
    public static function DelAddress($input)
    {
        try {
            $res = Db::table(self::$_user_address_table)->where('id', $input['id'])->update(['status' => 3]);
            if ($res != 0) return jsonSuccess('删除成功', $res);
            return jsonFail('删除成功');
        } catch (\Exception $e) {
            return jsonFail($e->getMessage());
        }
    }
}